package com.lxr0860.lxr0860production_test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;


import com.lxr0860.lxr0860production_test.bean.LogItemBean;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.ShareUtils;
import com.lxr0860.lxr0860production_test.utils.ToastUtils;
import com.lxr0860.lxr0860production_test.view.TableView;
import com.sdk.devicemanager.DEVICEcon;

import org.jetbrains.annotations.Nullable;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Created by uniriho on 2018/9/18.
 */

public class TestRecordActivity extends Activity implements View.OnClickListener{
    private ImageButton mIbReset;
    private TableView mTableView;
    private TextView mTvFlowNumber;
    private DEVICEcon devicEcon;
    private File file_log;
    private boolean destroy;
    private UpdateUiThread mThread;
    private List<LogItemBean> logItems;
    private ArrayList<LogItemBean> temList=null;
    private boolean uiLoadCompleted;
    private int testType;

    private static final int UPDATE_UI=1;
    @SuppressLint("HandlerLeak")
    private final Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE_UI:
                    for(int i=0;i<logItems.size();i++){
                        mTableView.addContent(logItems.get(i).getTestType(),
                                logItems.get(i).getTestItem(),
                                logItems.get(i).getTestState());
                    }
                    mTableView.refreshTable();
                    break;
                case Contants.DIALOG_POSITIVE:
                    if(uiLoadCompleted){
                        if(resetRecord()){
                            mTableView.clearTableContents();
                            if(testType!= Contants.TEST_QIANGHUA){
                                mTableView.setHeader("测试类型","测试子项","测试状态");
                                Intent mIntent=new Intent();
                                Bundle bundle=new Bundle();
                                bundle.putBoolean("result",true);
                                mIntent.putExtras(bundle);
                                TestRecordActivity.this.setResult(Contants.TEST_JILU,mIntent);
                            }else {
                                mTableView.setHeader("测试项","测试结果","测试时间");
                            }
                            mTableView.refreshTable();
                            ShareUtils.INSTANCE.clearTestCount(TestRecordActivity.this);
                        }else {
                            ToastUtils.showMessage("重置失败");
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_test_record);
        initView();
        initData();
        initEvent();
    }

    private void initView(){
        mIbReset= (ImageButton) findViewById(R.id.ib_reset_record);
        mTableView= (TableView) findViewById(R.id.tabv_recorde_table);
        mTvFlowNumber= (TextView) findViewById(R.id.tv_flow_number);
    }

    private void initData(){
        testType=getIntent().getIntExtra("testType", Contants.TEST_JILU);
        mTableView.clearTableContents();
        if(testType== Contants.TEST_QIANGHUA){
            mTableView.setHeader("测试项","测试结果","测试时间");
            file_log=new File(Contants.LOG_STRENGTH_PATH);
        }else {
            devicEcon=new DEVICEcon(this);
            DEVICEcon devicEcon1 = new DEVICEcon(this);
            mTvFlowNumber.setText("流水号:" + devicEcon1.get_sys_parameter(1));
            mTableView.setHeader("测试类型","测试子项","测试状态");
            file_log=new File(Contants.LOG_FACTORY_PATH);
        }
        mTableView.refreshTable();
        logItems=new ArrayList<LogItemBean>();
        uiLoadCompleted=false;
        if(mThread==null){
            mThread=new UpdateUiThread();
            mThread.start();
        }
    }
    private void initEvent(){
        mIbReset.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy=true;
        handler.removeMessages(UPDATE_UI);
        if(mThread!=null){
            mThread.interrupt();
            mThread=null;
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId()== R.id.ib_reset_record){
            Contants.showDailog(this,"是否重置测试记录",handler, Gravity.CENTER);
        }
    }

    private boolean resetRecord(){
        boolean resetSuccess=true;
        File diwen=new File(Contants.LOG_DIWEN_DELAY_PATH);
        if(diwen.exists()){
            resetSuccess=diwen.delete();
        }
        if(file_log.exists()){
            if(file_log.isFile()){
                resetSuccess =file_log.delete();
            }else {
                File[] files = file_log.listFiles();
                for(File file:files){
                    file.delete();
                }
            }
        }
        if(file_log.exists()&&file_log.isDirectory()){
            resetSuccess=!(file_log.listFiles().length>0);
        }
        return resetSuccess;
    }

    private class UpdateUiThread extends Thread {
        @Override
        public void run() {
            if(file_log.exists()){
                BufferedReader bufr=null;
                try {
                    if(file_log.isDirectory()){
                        //常规测试记录
                        File[] files= file_log.listFiles();
                        files=sortFiles(files);
                        if(files==null){
                            return;
                        }
                        for(int i=0;i<files.length;i++){
                            if(destroy){
                                return;
                            }
                            if(i>0){
                                logItems.add(new LogItemBean("","",""));
                            }
                            if(temList==null){
                                temList=new ArrayList<>();
                            }else {
                                temList.clear();
                            }
                            bufr= new BufferedReader(new FileReader(files[i]));
                            String line;
                            while ((line = bufr.readLine()) != null) {
                                if(destroy){
                                    return;
                                }
                                if(line.length()>0){
                                    LogItemBean logItem=new LogItemBean();
                                    logItem.setTestType(Contants.getTopTitle
                                            (Integer.parseInt(files[i].getName()
                                                    .substring(0,files[i].getName()
                                                            .lastIndexOf(".")))));
                                    if(!line.equals("true")){
                                        logItem.setTestItem(Contants.itemTitles
                                                [Integer.parseInt(line.substring(1))]);
                                        logItem.setTestState("测试完成");
                                    }else {
                                        temList.clear();
                                        logItem.setTestItem("全部项目");
                                        logItem.setTestState("测试完成");
                                    }
                                    temList.add(logItem);
                                }
                            }
                            bufr.close();
                            for(LogItemBean bean:temList){
                                logItems.add(bean);
                            }
                        }
                    }else {
                        //强化测试记录
                        bufr= new BufferedReader(new FileReader(file_log));
                        String line;
                        while ((line = bufr.readLine()) != null) {
                            if(destroy){
                                return;
                            }
                            if(line.length()>0&&line.contains("/")){
                                String[] split = line.split("/");
                                LogItemBean logItem=new LogItemBean();
                                for(int i=0;i<split.length;i++){
                                    if(i==0){
                                        logItem.setTestType(split[i]);
                                    }else if(i==1){
                                        logItem.setTestItem(split[i]);
                                    }else {
                                        logItem.setTestState(split[i]);
                                    }
                                }
                                logItems.add(logItem);
                            }
                        }
                        bufr.close();
                    }
                    handler.sendEmptyMessage(UPDATE_UI);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(bufr!=null){
                        try {
                            bufr.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            uiLoadCompleted=true;
        }
    }

    private File[] sortFiles(File[] files){
        if(files==null||files.length<=0){
            return null;
        }
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        return files;
    }
}
